import React from "react";
import {
    Animated,
    Image,
    Keyboard,
    Modal,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
} from "react-native";
import screen from "../../utils/screen";
import Constants from "../../utils/Constants";
import { AppInfo, FontFamily, getffly } from "../../utils/common";
import Images from "../../images/Images";
import DeviceInfo from "react-native-device-info";
import RequestUtil from "../../utils/RequestUtil";
import Api from "../../utils/Api";
import { inject, observer } from "mobx-react";
import DialogTip from "../../widgets/modal/DialogTip";
import store from "../../utils/SimpleStore";
import RegisterView from "../../components/RegisterView";
import { AlertModal } from "../../widgets/modal";


const tabTitles = [Constants.login.register_tab ,Constants.login.login_tab]


@inject(['userStore'])
@observer
export default class Login extends React.Component{

    state={
        modalVisible:false,
        currentPage: 1,
        mobileText:'',
        codeText:'',
        pswText:'',
        loginEnable:false,
        eyeOpen:false,
        sendTime:0,
    }



    componentDidMount(){

    }


    getLoginInfo = ()=>{
        store.get('login_info').then(res=>{
            if(res){
                // console.log('login info',res)
                const {mobile,password} = res
                this.setState({
                    mobileText:mobile,
                    pswText:password,
                    loginEnable:true
                })
            }
        })
    }

    reset = ()=>{
        this.setState({
            mobileText:'',
            codeText:'',
            pswText:'',
            loginEnable:false,
            eyeOpen:false
        })
    }

    show = ()=>{
        this.setState({
            modalVisible:true
        })
        this.reset();
        this.getLoginInfo()
    }

    close = ()=>{
        this.setState({
            modalVisible:false
        })
    }

    checkEnable = ()=>{
        if(this.state.currentPage === 1){
            console.log('check enable')
            if(this.state.mobileText.length > 0 && this.state.pswText.length > 0){
                this.setState({
                    loginEnable:true
                })
            }else{
                this.setState({
                    loginEnable:false
                })
            }
        }else{

        }

    }

    login = (mobile,password)=>{
        Keyboard.dismiss()
        let data1 = {}
        data1["receiverType"] = "cellphone";
        data1["receiverArea"] = AppInfo.countryId;
        data1["receiverId"] = mobile;
        data1["password"] = password;
        data1["version"] = '1.0';


        console.log('login param',data1)
        this.tipDialog.showLoading();
        this.props.userStore.login(data1,(data)=>{
            this.props.loginSuccess && this.props.loginSuccess();
            this.tipDialog.hideDialog()
            this.close()
        },(error)=>{

            this.tipDialog.hideDialog()
            this.tipDialog.showTip(error.msg)

        })

    }

    countDown = ()=>{
        this.timer && clearInterval(this.timer)
        this.timer = setInterval(()=>{
            let time  = this.state.sendTime - 1
            if(time >= 0){
                this.setState({
                    sendTime:time
                })
            }else{
                this.timer && clearInterval(this.timer)
                this.setState({
                    sendTime:0
                })
            }
        },1000)
    }


    sendCode = (phone)=>{
        Keyboard.dismiss()
        let param = {
            receiverType:'cellphone',
            receiverArea:AppInfo.countryId,
            receiverId:phone
        }
        console.log('send code param',param)
        this.tipDialog.showLoading();
        RequestUtil.post(Api.sendCodeRegister,param,true).then(res=>{
            console.log('send code',res)
            const data =res.data
            this.tipDialog.hideDialog()
            this.setState({
                codeText:data.code ? data.code : '',
                sendTime:60
            },()=>{
                this.countDown()
            })


        },error=>{
            this.tipDialog.hideDialog()
            this.tipDialog.showTip(error.msg)
        })
    }


    register = (data)=>{
        Keyboard.dismiss()
        let {phone,code,referralCode,psw} = data
        let param = {
            receiverType:'cellphone',
            receiverArea:AppInfo.countryId,
            receiverId:phone,
            password:psw,
            code:code,
        }
        if(AppInfo.channel && AppInfo.channel !== ''){
            param["inviteCode"] = AppInfo.channel
        }else{
            param["inviteCode"] = referralCode
        }

        // param["clientType"] = "web";
        // param["clientId"] = '12345000';
        // param["deviceInfo"] = 'web';
        // param["osInfo"] = '1' + "-" + '1';
        // param["version"] = '1.0';
        console.log('register ',param)

        this.tipDialog.showLoading();
        RequestUtil.post(Api.register,param,true).then(res=>{
            console.log('register',res)
            this.tipDialog.hideDialog()
            if(res.code === 0){
                this.tipDialog.showSuccess(res.msg)
                this.login(phone,psw)
            }

        },error=>{
            this.tipDialog.hideDialog()
            if(error.code == -7){
                this.alertModal.alert('Error',error.msg,[
                    {
                        title:'Change',
                        onPress:()=>{
                            this.alertModal.hideDialog()
                        }
                    },{
                        title:'Login',
                        onPress:()=>{
                            this.alertModal.hideDialog()
                            this.setState({
                                currentPage:1
                            })
                        }
                    }
                ])
            }else{
                this.tipDialog.showTip(error.msg)
            }

        })
    }

    renderTabBar(){
        return (
            <View style={styles.header}>
                {
                    tabTitles.map((item,index)=>{
                        const isSelect = this.state.currentPage === index
                        return (
                            <TouchableOpacity
                                key={index.toString()}
                                onPress={()=>{
                                    this.setState({
                                        currentPage:index
                                    })
                                }}
                            >
                                <Text style={isSelect ? styles.titleTextSelect : styles.titleText}>{item}</Text>
                            </TouchableOpacity>
                        )
                    })
                }

                <Animated.View style={{left:  this.state.currentPage * screen.PIXEL_200,
                    width:screen.PIXEL_200,alignItems:'center',
                    position: 'absolute',bottom:0
                }}>
                    <View style={styles.tabLine}/>
                </Animated.View>

            </View>
        )
    }


    renderLoginView = ()=>{
        return (
            <View style={{width:'100%',marginTop:screen.PIXEL_30}}>

                <Text style={styles.mobileTitle}>{Constants.login.mobile_title}</Text>

                <View style={styles.inputWrap}>
                    <TextInput
                        keyboardType='numeric'
                        allowFontScaling={false}
                        placeholderTextColor={'rgba(255, 255, 255, 0.35)'}
                        placeholder={Constants.login.mobile_login}
                        style={ styles.mobileInput}
                        value={this.state.mobileText}
                        onChangeText={(text) => {
                            this.setState({
                                mobileText: text
                            },this.checkEnable)
                        }}
                    />

                    {
                        this.state.mobileText.length > 0 ? (
                            <TouchableOpacity
                                style={styles.clearBtn}
                                onPress={()=>{
                                    this.setState({
                                        mobileText:''
                                    })
                                    this.checkEnable()
                                }}
                            >
                                <Image source={Images.clear} style={{width:screen.PIXEL_15,height:screen.PIXEL_15}}/>
                            </TouchableOpacity>
                        ):null
                    }

                </View>


                <Text style={[styles.mobileTitle,{marginTop:screen.PIXEL_40}]}>{Constants.login.password}</Text>

                <View style={styles.inputWrap}>
                    <TextInput
                        // keyboardType='numeric'
                        allowFontScaling={false}
                        placeholderTextColor={'rgba(255, 255, 255, 0.35)'}
                        placeholder={Constants.login.password}
                        secureTextEntry={!this.state.eyeOpen}
                        style={ styles.mobileInput}
                        value={this.state.pswText}
                        onChangeText={(text) => {
                            this.setState({
                                pswText: text
                            },this.checkEnable)
                        }}
                    />

                    <TouchableOpacity
                        style={styles.eyeBtn}
                        onPress={()=>{
                            this.setState({
                                eyeOpen:!this.state.eyeOpen
                            })
                        }}
                    >
                        <Image source={this.state.eyeOpen ? Images.eye_open : Images.eye_close}
                               resizeMode={'contain'}
                               style={{width:screen.PIXEL_40,height:screen.PIXEL_40}}/>
                    </TouchableOpacity>

                </View>


                <Text style={{color:'#FF7B14',fontSize:12,alignSelf:'flex-end'}}
                      onPress={()=>{
                          this.close()
                          this.props.navigation.navigate('ResetPsw',{mobile:this.state.mobileText})
                      }}
                >{Constants.login.reset}</Text>

                {
                    this.state.loginEnable ? (
                        <TouchableOpacity
                            onPress={()=>this.login(this.state.mobileText,this.state.pswText)}
                            style={[styles.nextBtn,{
                                backgroundColor:  '#377C74'
                            }]}
                        >
                            <Text style={{color:'#fff',fontSize:16}}>{Constants.login.continue}</Text>
                        </TouchableOpacity>
                    ) : (
                        <View style={styles.nextBtn} >
                            <Text style={{color:'#fff',fontSize:16}}>{Constants.login.continue}</Text>
                        </View>
                    )
                }



            </View>
        )
    }


    render(){
        return (
            <Modal
                animationType={'none'}
                transparent={true}
                visible={this.state.modalVisible}
                onRequestClose={() => {
                    this.setState({
                        modalVisible:false
                    })
                }}
                onShow={this.startShow}
            >
                <StatusBar barStyle='light-content' translucent={true} backgroundColor="rgba(16, 17, 22,0.75)" animated={false}/>
                <TouchableOpacity
                    activeOpacity={1.0}
                    onPress = { () => {

                    }}
                    style={styles.bottomcontainer}>

                    <View style={styles.content}>

                        {this.renderTabBar()}

                        {this.state.currentPage === 1 ? this.renderLoginView() : (
                            <ScrollView
                                showsVerticalScrollIndicator={false}
                            >
                                <RegisterView
                                    ref={this.registerViewRef}
                                    codeText={this.state.codeText}
                                    sendTime={this.state.sendTime}
                                    onSend={(phone)=>this.sendCode(phone)}
                                    onNext={(data)=>this.register(data)}
                                />
                            </ScrollView>
                        )}
                    </View>

                    <TouchableOpacity
                        style={{marginTop:screen.PIXEL_20}}
                        onPress={this.close}
                    >
                        <Image source={Images.close} style={styles.close}/>
                    </TouchableOpacity>


                    <DialogTip ref={ref=>this.tipDialog = ref} />
                    <AlertModal ref={ref=>this.alertModal = ref}/>

                </TouchableOpacity>



            </Modal>
        )
    }
}




const styles = StyleSheet.create({
    container: {
        flex:1,
    },
    bottomcontainer: {
        zIndex:2,
        flex: 1,
        alignItems: 'center',
        backgroundColor:'rgba(16, 17, 22,0.75)',
        justifyContent:'center',
    },
    bottomcontainer1: {
        zIndex:3,
        width: screen.width,
        height: screen.height,
        borderTopRightRadius:screen.scaleSize(24),
        borderTopLeftRadius:screen.scaleSize(24),
        backgroundColor:'#FFFFFF',
        // backgroundColor:'red',
        position: 'absolute',
        bottom:-screen.height,
        // bottom:0,
        alignItems:'center',
        flexDirection:'column'
        // transform: [{translateY:-c_deviceHeight}]
    },
    content:{
        marginHorizontal:screen.PIXEL_60,
        borderRadius:screen.PIXEL_40,
        backgroundColor:'#fff',
        width:screen.width - screen.PIXEL_120,
        paddingHorizontal:screen.PIXEL_50,
        paddingVertical:screen.PIXEL_30
    },
    header:{
        flexDirection: 'row',height:screen.PIXEL_80
    },
    titleText:{
        color:'#A9A9A9',fontWeight:'bold',fontSize:19,width:screen.PIXEL_200,textAlign: 'center'
    },
    titleTextSelect:{
        color:'#377C74',fontWeight:'bold',fontSize:19,width:screen.PIXEL_200,textAlign:'center'
    },
    tabLine:{
        height:2,backgroundColor:'#377C74',width:screen.PIXEL_200,
    },
    close:{
        width:screen.PIXEL_70,
        height:screen.PIXEL_70
    },
    mobileTitle:{
        fontSize:12,color:'#000',fontFamily:getffly(FontFamily.regular)
    },
    inputWrap:{
        width:'100%',
        height:screen.PIXEL_90,
        flexDirection:'row',
        borderBottomWidth:1,
        borderBottomColor:'rgba(32,32,32,0.3)'
    },
    codeInputWrap:{
        width:'100%',
        height:screen.PIXEL_90,
        flexDirection:'row',
    },
    mobileInput:{
        fontFamily: getffly(FontFamily.bold),
        flex:1,
        fontSize:20,
        color:'#377C74',
        marginRight:screen.PIXEL_60
    },
    codeInput:{
        fontFamily: getffly(FontFamily.bold),
        flex:1,
        fontSize:20,
        color:'#000',
        marginRight:6,
        borderBottomWidth:1,
        borderBottomColor:'rgba(32,32,32,0.3)'
    },
    clearBtn:{
        width:screen.PIXEL_50,
        height:screen.PIXEL_50,
        position:'absolute',
        right:0,
        top:screen.PIXEL_20,
        justifyContent: 'center',
        alignItems:'center'
    },
    eyeBtn:{
        width:screen.PIXEL_50,
        height:screen.PIXEL_50,
        position:'absolute',
        right:0,
        top:screen.PIXEL_20,
        justifyContent: 'center',
        alignItems:'center'
    },
    eyeImage:{
        width:screen.PIXEL_40,height:screen.PIXEL_40
    },
    pswInput:{

    },
    sendBtn:{
        width:screen.PIXEL_160,height:screen.PIXEL_90,borderWidth:1,
        borderColor:'#377C74',borderRadius: screen.PIXEL_20,
        justifyContent: 'center',
        alignItems:'center'
    },
    nextBtn:{
        height:screen.PIXEL_90,width:'100%',backgroundColor:'#C8C8C8',justifyContent:'center',alignItems:'center',
        marginTop:screen.PIXEL_30,borderRadius:screen.PIXEL_20
    }
})
